var dealerCode = getQueryParamValue("dealerCode");
var regionName = getQueryParamValue("regionName");
$(document).ready(function(){
	$("#KmFirst").hide();
	var rootPath = getRootPath();
	$("#dealerCode").val(dealerCode);
	
	//监听城市选择页面搜索输入框
	$("#cha").keyup(function(event){ 
        if (event.keyCode === 13){ 
       	 searchCity();
        } 
      }); 
	
	//监听经销商选择页面搜索输入框
	$("#sou").keyup(function(event){ 
        if (event.keyCode === 13){ 
       	 searchDealer();
        } 
      }); 

});
//选择经销商，点击
function selectMaintainDealer(obj){
	$("#cha").val("");
	$("#dealerMap").show();
	$("#KmFirst").hide();
	$("#nowDealerDiv").hide();
	$("#nowDealerDiv").removeClass("active in");
	 $("#maintainDealerDiv").show();
	 //初始化界面
	 $("#maintainDealerDiv").addClass("active in");
		
		// 选择经销商城市信息取得。
		$.ajax({
			headers: {'Cookie' : document.cookie },
			method : 'get',
			url : rootPath+'/maintain/api/v1/maintainDealerMap?regionType=90011002',
			error:function(XMLHttpRequest, ajaxOptions, thrownError){
				//alert("获取失败!");
			},
			success : function(resultData){

				var wholeHtml = '';
				
				var city = '';
				$.each(resultData,function(maintainDealerMapIndex,maintainDealerMapObj){
					var DealerMapHtml = '';
					var str = maintainDealerMapObj.regionName;
					if(str == "") return;
					var arr = maintainDealerMapObj.aleph;
					for(var i=0;i<26;i++){
						var en = String.fromCharCode((97+i));
						if(arr == en){
							city = maintainDealerMapObj.regionName;

							DealerMapHtml = DealerMapHtml + '<li>'
														  + '<a onclick="selectDealer('+ maintainDealerMapIndex +')">'
														  + '<span style="font-size:18px;color:#7a7a7a">' + city + '</span>'
														  + '<input type="hidden" id="'+maintainDealerMapIndex + '" value="'+ maintainDealerMapObj.regionName +'">'
														  + '</a>'
														  + '</li>'
														  + '<div style="height:1px;margin:0px auto;padding:0px;background-color:#F4F4F4;overflow:hidden;"></div>'
							
							$("#"+en).append(DealerMapHtml);
						}
					}
				});

			}
		});
}
function selectDealer(obj){
	$("#sou").val("");
	var code = $("#"+obj).val();
	$("#regionName").val(code);
	$("#maintainDealerDiv").hide();
	$("#maintainDealerDiv").removeClass("active in");
	$("#dealerDiv").html("");
	 $("#nowDealerDiv").show();
	 $("#searchCity").html("");
	 $("#searchDealer").html("");
	 $("#list2").show();
	 //初始化界面
	 $("#nowDealerDiv").addClass("active in");
	 for(var i=0;i<26;i++){
			var en = String.fromCharCode((97+i));
			$("#"+en).html("");
	 }
	//根据编号获取所在地经销商列表
	$.ajax({
		headers: {'Cookie' : document.cookie },
		method : 'get',
		url : rootPath+'/maintain/api/v1/maintainDealer?regionName='+code+'&dealerCode='+$("#dealerCode").val(),
		error:function(XMLHttpRequest, ajaxOptions, thrownError){
			//alert("未连接服务器!");
		},
		success : function(resultData){
			
			var wholeHtml = '';
			var  Km = '';
			$.each(resultData,function(maintainDealerIndex,maintainDealerObj){
				
				var findDealerHtml = '';
				var lat1 = maintainDealerObj.latitude;
				var lng1 = maintainDealerObj.longitude;
				var lat2 = $("#latitude").val();
				var lng2 = $("#longitude").val();
				Km = GetDistance(lat1,lng1,lat2,lng2).toFixed(2);
				if(lat1==null||lat1=="0"||lng1==null||lng1=="0"){var distance = "暂无";}
				else{var distance = Km + '千米';}
				
					if(maintainDealerObj.remark =='首选店'){
						$("#KmFirst").show();
						$("#nameFirst").html(maintainDealerObj.dealerShortName);
						$("#distanceFirst").html(distance);
						$("#addrFirst").html(maintainDealerObj.detailAddress);
						$("#codeFirst").val(maintainDealerObj.dealerCode);
						$('#Tel').attr('href',maintainDealerObj.serviceHotline);
						$("#remarkFirst").html(maintainDealerObj.remark);
					}else{
				findDealerHtml = findDealerHtml + '<li data-id="'+ Km +'">'
												+ '<div class="panel panel-default">'
												+ '<table style="width:100%" class="table-condensed"><tbody>'
												+ '<tr>'
												+ '<td style="width:160px;text-align:left;"><a onclick="sureDealer('+maintainDealerIndex+')">'
												+ '<p id="name'+ maintainDealerIndex +'" style="font-family:黑体;font-size:16px;color:#000000">' + maintainDealerObj.dealerShortName + '</p>'
												+ '</a></td>'
												+ '<td style="width:100px;text-align:center;font-size:14px;color:#7a7a7a">'
												+ '<span>距离：</span><span>'+ distance + '</span>'
												+ '</td>'
												+ '</tr><tr>'
												+ '<td style="width:160px;text-align:left;">'
												+ '<span id="addr'+ maintainDealerIndex +'" style="font-faminly:宋体;font-size:15px;color:#615f5f">' + maintainDealerObj.detailAddress + '</span>'
												+ '</td>'
												+ '<td style="width:100px;text-align:center;">'
												+ '<a href="tel:'+ maintainDealerObj.serviceHotline +'" id="Tel">'
												+ '<span class="glyphicon glyphicon-earphone" style="color: rgb(255, 0, 23); font-size: 12px;"></span>'
												+ '<span style="font-family:宋体;font-size:14px;color:#7a7a7a"> 电话</span>'
												+ '</a></td>'
												+ '</tr>'
												+ '</tbody></table>'
												+ '<input id="code'+ maintainDealerIndex +'" class="hidden" value="' + maintainDealerObj.dealerCode + '">'
												+ '</div></li>'
				
				wholeHtml += findDealerHtml;
				}
			});
			$("#dealerDiv").append(wholeHtml);
		}
	});
}
//排序
function Sort(bo)
{
    var arr = document.getElementById("list2").innerHTML.match(/<li>[\s\S]+?<\/li>/g);
    arr.sort(function(a,b){
        a = parseInt(/\d+/.exec(a)[0], 10);
        b = parseInt(/\d+/.exec(b)[0], 10);
        return bo?b-a:a-b;
    });
    document.getElementById("ol1").innerHTML = arr.join("");
}
//搜索城市
function searchCity(){
	$("#dealerMap").hide();
	$("#searchCity").html("");
	var regionName = $("#cha").val();
	$.ajax({
		headers: {'Cookie' : document.cookie },
	    type:"GET", 
	    url:rootPath+"/maintain/api/v1/maintainSelectCity?regionName="+regionName, 
	    dataType:"json",      
	    async: false,
	    contentType:"application/json",               
	    data:null, 
	    success:function(data){ 
			var wholeHtml = '<ul class="list-group">';
			
			$.each(data,function(maintainSearchCityIndex,maintainSearchCityObj){
				var DealerMapHtml = '';
				
					DealerMapHtml = DealerMapHtml   + '<li class="list-group-item">'
													+ '<a onclick="selectDealer('+ maintainSearchCityIndex +')">'
													+ '<span style="font-size:18px;color:#7a7a7a">' + maintainSearchCityObj.regionName + '</span>'
													+ '<input type="hidden" id="'+maintainSearchCityIndex + '" value="'+ maintainSearchCityObj.regionName +'">'
													+ '</a>'
													+ '</li>'		
				       wholeHtml += DealerMapHtml;
			});
			wholeHtml = wholeHtml + '</ul>'
			$("#searchCity").append(wholeHtml);
	    },
	    error:function(data){
	    	//alert("数据刷新失败，请联系管理员！");
	    }
	 });
}
//搜索经销商
function searchDealer(){
	$("#list2").hide();
	$("#searchDealer").html("");
	var dealerName = $("#sou").val();
	var regionName = $("#regionName").val();
	$.ajax({
		headers: {'Cookie' : document.cookie },
	    type:"GET", 
	    url:rootPath+"/maintain/api/v1/searchDealer?dealerName="+dealerName+"&regionName="+regionName, 
	    dataType:"json",      
	    async: false,
	    contentType:"application/json",               
	    data:null, 
	    success:function(data){ 
			var wholeHtml = '<ul class="list-group">';
			var  Km = '';
			$.each(data,function(SearchDealerIndex,SearchDealerObj){
				var DealerMapHtml = '';
				var findDealerHtml = '';
				var lat1 = SearchDealerObj.latitude;
				var lng1 = SearchDealerObj.longitude;
				var lat2 = $("#latitude").val();
				var lng2 = $("#longitude").val();
				Km = GetDistance(lat1,lng1,lat2,lng2).toFixed(2);
				if(lat1==null||lat1=="0"||lng1==null||lng1=="0"){var distance = "暂无";}
				else{var distance = Km + '千米';}
				
					DealerMapHtml = DealerMapHtml   + '<li class="list-group-item">'
													+ '<table style="width:100%" class="table-condensed"><tbody>'
													+ '<tr>'
													+ '<td style="width:160px;text-align:left;"><a onclick="sureDealer('+SearchDealerIndex+')">'
													+ '<p id="name'+ SearchDealerIndex +'" style="font-family:黑体;font-size:16px;color:#000000">' + SearchDealerObj.dealerShortName + '</p>'
													+ '<p class="hidden" id="shortName'+SearchDealerIndex+'">'+SearchDealerObj.dealerShortName+'</p>'
													+ '</a></td>'
													+ '<td style="width:100px;text-align:center;font-size:14px;color:#7a7a7a">'
													+ '<span>距离：</span><span>'+ distance + '</span>'
													+ '</td>'
													+ '</tr><tr>'
													+ '<td style="width:160px;text-align:left;">'
													+ '<span id="addr'+ SearchDealerIndex +'" style="font-faminly:宋体;font-size:15px;color:#615f5f">' + SearchDealerObj.detailAddress + '</span>'
													+ '</td>'
													+ '<td style="width:100px;text-align:center;">'
													+ '<a href="tel:'+ SearchDealerObj.serviceHotline +'" id="Tel">'
													+ '<span class="glyphicon glyphicon-earphone" style="color: rgb(255, 0, 23); font-size: 12px;"></span>'
													+ '<span style="font-family:宋体;font-size:14px;color:#7a7a7a"> 电话</span>'
													+ '</a></td>'
													+ '</tr>'
													+ '</tbody></table>'
													+ '<input id="code'+ SearchDealerIndex +'" class="hidden" value="' + SearchDealerObj.dealerCode + '">'
													+ '</li>'
											
					wholeHtml += DealerMapHtml;
			});
			wholeHtml = wholeHtml + '</ul>'
			$("#searchDealer").append(wholeHtml);
	    },
	    error:function(data){
	    	//alert("数据刷新失败，请联系管理员！");
	    }
	 });
}
function sureDealer(obj){
	if(obj=='-1'){
		  var code = $("#codeFirst").val();
	 	  var name = $("#shortNameFirst").html();
	   	  var addr = $("#addrFirst").html();
		}else{
		  var code = $("#code"+obj).val();
		  var name = $("#shortName"+obj).html();
		  var addr = $("#addr"+obj).html();
		}
	//alert(code+','+name+','+addr);
	var dealerDto = {"dealerCode":$("#dealerCode").val()};
	$.ajax({
		headers: {'Cookie' : document.cookie }, 
        type:"POST", 
        url:rootPath+"/customer/api/v1/dealerCode", 
        dataType:"json",      
        contentType:"application/json",               
        data:JSON.stringify(dealerDto), 
        success:function(data){ 
        	alert("修改经销商成功！");
        },
        error:function(data){
        	//alert("预约失败！");
        }
     });
}
function first(obj){
	
	 $("#sou").val("");
	 $("#maintainDealerDiv").hide();
	 $("#maintainDealerDiv").removeClass("active in");
	 $("#nowDealerDiv").show();
	 $("#dealerDiv").html("");
	 //初始化界面
	 $("#nowDealerDiv").addClass("active in");
		//根据编号获取所在地经销商列表
			$.ajax({
				//headers: {'Cookie' : document.cookie },
				method : 'get',
				url : rootPath+'/maintain/api/v1/maintainDealer?regionName='+ obj +'&dealerCode='+dealerCode,
				error:function(XMLHttpRequest, ajaxOptions, thrownError){
					//alert("未连接服务器!");
				},
				success : function(resultData){
					
					var wholeHtml = '';
					var  Km = '';
					$.each(resultData,function(maintainDealerIndex,maintainDealerObj){
						
						var findDealerHtml = '';
						var lat1 = maintainDealerObj.latitude;
						var lng1 = maintainDealerObj.longitude;
						var lat2 = $("#latitude").val();
						var lng2 = $("#longitude").val();
						Km = GetDistance(lat1,lng1,lat2,lng2).toFixed(2);
						if(lat1==null||lat1=="0"||lng1==null||lng1=="0"){var distance = "暂无";}
						else{var distance = Km + '千米';}
						
							if(maintainDealerObj.remark =='首选店'){
								$("#KmFirst").show();
								$("#nameFirst").html(maintainDealerObj.dealerShortName);
								$("#distanceFirst").html(distance);
								$("#addrFirst").html(maintainDealerObj.detailAddress);
								$("#codeFirst").val(maintainDealerObj.dealerCode);
								$('#Tel').attr('href',maintainDealerObj.serviceHotline);
								$("#remarkFirst").html(maintainDealerObj.remark);
							}else{
						findDealerHtml = findDealerHtml + '<li data-id="'+ Km +'">'
														+ '<div class="panel panel-default">'
														+ '<table style="width:100%" class="table-condensed"><tbody>'
														+ '<tr>'
														+ '<td style="width:160px;text-align:left;"><a onclick="sureDealer('+maintainDealerIndex+')">'
														+ '<p id="name'+ maintainDealerIndex +'" style="font-family:黑体;font-size:16px;color:#000000">' + maintainDealerObj.dealerShortName + '</p>'
														+ '</a></td>'
														+ '<td style="width:100px;text-align:center;font-size:14px;color:#7a7a7a">'
														+ '<span>距离：</span><span>'+ distance + '</span>'
														+ '</td>'
														+ '</tr><tr>'
														+ '<td style="width:160px;text-align:left;">'
														+ '<span id="addr'+ maintainDealerIndex +'" style="font-faminly:宋体;font-size:15px;color:#615f5f">' + maintainDealerObj.detailAddress + '</span>'
														+ '</td>'
														+ '<td style="width:100px;text-align:center;">'
														+ '<a href="tel:'+ maintainDealerObj.serviceHotline +'" id="Tel">'
														+ '<span class="glyphicon glyphicon-earphone" style="color: rgb(255, 0, 23); font-size: 12px;"></span>'
														+ '<span style="font-family:宋体;font-size:14px;color:#7a7a7a"> 电话</span>'
														+ '</a></td>'
														+ '</tr>'
														+ '</tbody></table>'
														+ '<input id="code'+ maintainDealerIndex +'" class="hidden" value="' + maintainDealerObj.dealerCode + '">'
														+ '</div></li>'
						
						wholeHtml += findDealerHtml;
						}
					});
					$("#dealerDiv").append(wholeHtml);
				}
			});
}
//进行经纬度转换为距离的计算
function Rad(d){
  return d * Math.PI / 180.0;//经纬度转换成三角函数中度分表形式。
}
//计算距离，参数分别为第一点的纬度，经度；第二点的纬度，经度
function GetDistance(lat1,lng1,lat2,lng2){

   var radLat1 = Rad(lat1);
   var radLat2 = Rad(lat2);
   var a = radLat1 - radLat2;
   var  b = Rad(lng1) - Rad(lng2);
   var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
   Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
   s = s *6378.137 ;// EARTH_RADIUS;
   s = Math.round(s * 10000) / 10000; //输出为公里
   //s=s.toFixed(4);
   return s;
}